#include "Arrow.h"
#include "../Doohickeys/Entity.h"

#include <math.h>

bitmapImage* Arrow::images = NULL;

Arrow::Arrow(Map* map) : 
	map(map),
	imageLoc(Point<int>(-1, -1)),
	range(340.0),
	vect(vect),  
	team(0),
	target(NULL)
	{
		loadBitmap();
	}

void Arrow::loadBitmap() {
	if(images == NULL) {
		images = new bitmapImage();
		images->image = al_load_bitmap("rsc/Entity/Archer/a_arrow.tga");
		images->sizeX = 32;
		images->sizeY = 64;
	}
}

bool Arrow::inRange() {
	if(pos.x < -32 || pos.x >= map->numTilesX*map->tileSize + 32 ||
		pos.y < -32 || pos.y >= map->numTilesY*map->tileSize + 32)
		return false;
	if(pos.dist(startPos) > range)
		return false;
	return true;
}

void Arrow::startArrow(Point<float> p, Point<float> v, Doohickey* target) {
	if(target == NULL)
		return;

	pos = p;
	startPos = p;
	vect = v;
	ok = true;
	this->target = target;

	v.y = v.y*-1;
	
	imageLoc = Point<int>(-1, -1);

	//N, S, E, W
	if(v.x > -0.05 && v.x < 0.05) {
		if(v.y > 0)
			imageLoc = Point<int>(0, 0);
		else if(v.y < 0)
			imageLoc = Point<int>(4, 0);
	}
	else if(v.y > -0.05 && v.y < 0.05) {
		if(v.x > 0)
			imageLoc = Point<int>(3, 3);
		else if(v.x < 0)
			imageLoc = Point<int>(7, 3);
	}

	//if N,S,E, or W
	if(imageLoc.x != -1)
		return;


	//FIND NE, NW, SE, SW and angle
	//Find Y
	int column;
	if(v.x > 0 && v.y > 0)
		column = 0;
	else if(v.x < 0 && v.y > 0)
		column = 6;
	else if(v.x < 0 && v.y < 0)
		column = 4;
	else
		column = 2;

	float angle = abs(v.y/v.x);
	angle = atan(angle);
	angle = angle * 180 / ALLEGRO_PI;

	if(45 - angle <= 0) {
		angle -= 45;
	}
	else
		column++;

	int t = 45;
	if(column == 2 || column == 3 ||
		column == 6 || column == 7)
		t = 33.75;

	//Find X
	int closest = 0;
	float closestDist = abs(angle - t);
	float dist;
	cout << t << endl;
	t = t - 11.25;
	dist = abs(angle - t);
	if(dist < closestDist) {
		closestDist = dist;
		closest = 1;
	}
	t = t - 11.25;
	dist = abs(angle - t);
	if(dist < closestDist) {
		closestDist = dist;
		closest = 2;
	}
	t = t - 11.25;
	dist = abs(angle - t);
	if(dist < closestDist) {
		closest = 3;
	}

	imageLoc = Point<int>(column, closest);
}

void Arrow::update() {
	if(!ok)
		return;

	Point<float> newPos = pos + vect*5;

	if(!inRange()) {
		ok = false;
		return;
	}

	if(target != NULL)
		if(pos.dist(target->getPosition()) < 32) {
			ok = false;
			target->addToHealth(-5);
			return;
		}

	pos = newPos;
}

void Arrow::draw(Point<float> camXY) {
	int sizeX = images->sizeX;
	int sizeY = images->sizeY;
	al_draw_bitmap_region(images->image, imageLoc.x*sizeX, imageLoc.y*sizeY, 
		sizeX, sizeY, pos.x - camXY.x, pos.y - camXY.y, 0);
}

void Arrow::deleteImages() {
	al_destroy_bitmap(images->image);
	delete images;
}